package validator;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import command.UpdatePasswordForm;
import command.UserForm;
import domain.User;

@Component
public class UpdatePasswordFormValidator implements Validator {

	@Autowired
	private HttpSession session;
	@Autowired
	public UpdatePasswordFormValidator(HttpSession session) {
		this.session = session;
	}
	
	@Override
	public boolean supports(Class<?> clazz) {
		return UserForm.class.isAssignableFrom(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		UpdatePasswordForm form = (UpdatePasswordForm) target;
		
		User userlogged = (User)session.getAttribute("user");
		
		if(form.getCurrent()==null){
			errors.rejectValue("current", "empty");
		}else if (form.getCurrent().isEmpty()){
				errors.rejectValue("current", "empty");
		}else if(!form.getCurrent().equals(userlogged.getPassword())){
			errors.rejectValue("current", "notactual");
		}
		
		if(form.getPassword()==null || form.getPassword2()==null){
			errors.rejectValue("password", "empty");
		}else if(form.getPassword().isEmpty() || form.getPassword2().isEmpty()){
			errors.rejectValue("password", "empty");
			errors.rejectValue("password2", "empty");
		}else if(form.getPassword().length()>16 || form.getPassword2().length()>16){
			errors.rejectValue("password", "tooLong");
			errors.rejectValue("password2", "tooLong");			
		}else if(!form.getPassword().equals(form.getPassword2())){
			errors.rejectValue("password2", "confirmation");
		}
	}
}